/*
 * This project provides a number of implementations for indexing and evaluating
 * <i>Continuous Top-k Queries over Text Streams</i>
 * and has been developped as part of the work described in the article:
 * 
 * Vouzoukidou, N., Amann, B., & Christophides, V. (2012, October). 
 * Processing continuous text queries featuring non-homogeneous scoring functions.
 * In Proceedings of the 21st ACM international conference on Information and 
 * knowledge management (pp. 1065-1074). ACM.
 * http://dl.acm.org/citation.cfm?id=2398404
 * 
 * This software is distributed under the GNU General Public License and as an
 * additional condition of usage, please cite the aforementioned article.
 * 
 * Copyright (C) 2012 ICS/FORTH, Greece and 
 *               2012 LIP6, France
 * 
 * Author: Vouzoukidou Nelly, email: nelly.vouzoukidou (at) gmail (dot) com
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package gr.forth.ics.continuoustopk.metrics;

import gr.forth.ics.continuoustopk.Term;
import gr.forth.ics.continuoustopk.utils.MergedIterable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 *
 * @author Vouzoukidou Nelly, email: nelly.vouzoukidou (at) gmail (dot) com
 */
public enum SimilarityMetric {
    Jacard() {
        public double similarity(TermStatistics query, TermStatistics item) {
            int intersection = intersectionSize(query, item);
            return intersection / (query.termCount() + item.termCount() - (float) intersection);
        }
    },
    CosineProbabilities() {
        public double similarity(TermStatistics query, TermStatistics item) {
            Set<Term> union = union(query, item);
            double[] queryProb = new double[union.size()];
            double[] itemProb = new double[union.size()];
            int i = 0;
            for (Term term : union) {
                queryProb[i] = query.getWeight(term);
                itemProb[i] = item.getWeight(term);
                i++;
            }
            return 1 - cosine(queryProb, itemProb);
        }
    },
    Product() {
        public double similarity(TermStatistics query, TermStatistics item) {
            double sum = 0;
            for (Term term : query) {
                sum += query.getWeight(term) * item.getWeight(term);
            }
            return sum;
        }
    },
    Sorensen() {
        public double similarity(TermStatistics query, TermStatistics item) {
            return 2 * intersectionSize(query, item) / (query.termCount() + (float) item.termCount());
        }
    },
    KullbackLeibler() {
        public double similarity(TermStatistics query, TermStatistics item) {
            Set<Term> union = union(query, item);

            double distance = 0;
            for (Term term : union) {
                double queryProb = query.getWeight(term);
                double itemProb = item.getWeight(term);
                if (itemProb == 0) {
                    distance += queryProb * MAX_ALLOWED;
                } else if (queryProb != 0) {
                    distance += queryProb * Math.log(queryProb / itemProb);
                }
            }
            return 1 + distance;
        }
    },
    JensenShannon() {
        public double similarity(TermStatistics query, TermStatistics item) {
            TermStatistics merged = mergeCounter(query, item);
            return 1 - (KullbackLeibler.similarity(query, merged) + KullbackLeibler.similarity(item, merged)) / 2;
        }

        private TermStatistics mergeCounter(final TermStatistics query, final TermStatistics item) {
            return new TermStatistics() {

                public double getWeight(Term term) {
                    return (query.getWeight(term) + item.getWeight(term)) / 2;
                }

                public Iterator<Term> iterator() {
                    return new MergedIterable<Term>(query, item).iterator();
                }

                public int termCount() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    };

    
    //<editor-fold defaultstate="collapsed" desc="static fields">
    private static int MAX_ALLOWED = Integer.MAX_VALUE;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="usefull methods">
    private static double cosine(double[] v1, double[] v2) {
        double productV1V2 = 0;
        double distanceV1 = 0;
        double distanceV2 = 0;
        for (int i = 0; i < v1.length; i++) {
            productV1V2 += v1[i] * v2[i];
            distanceV1 += v1[i] * v1[i];
            distanceV2 += v2[i] * v2[i];
        }
        return 1 - productV1V2 / (Math.sqrt(distanceV1) * Math.sqrt(distanceV2));
    }

    private static Set<Term> union(Iterable<Term> terms1, Iterable<Term> terms2) {
        Set<Term> union = new HashSet<Term>();
        add(union, terms1);
        add(union, terms2);
        return union;
    }

    private static Set<Term> add(Set<Term> union, Iterable<Term> terms) {
        for (Term term : terms) {
            union.add(term);
        }
        return union;
    }
    
    private static int intersectionSize(TermStatistics query, TermStatistics item) {
        int intersection = 0;
        for (Term term : query) {
            if (item.getWeight(term) > 0) {
                intersection++;
            }
        }
        return intersection;
    }
    //</editor-fold>

    public abstract double similarity(TermStatistics query, TermStatistics item);
}
